package com.acme.bankapp.service.bank;

import com.acme.bankapp.domain.bank.Email;
import com.acme.bankapp.domain.bank.Queue;
import com.acme.bankapp.domain.bank.QueueImpl;

public class EmailService {

	private Queue queue = new QueueImpl();
	private static EmailService instance = new EmailService();
	private boolean closed;
	public EmailService() {
		new Thread( new Runnable() {
			@Override
			public void run() {
				while(!Thread.interrupted()) {
					sendNotificationEmail();
				}				
			}
		}).start();
	}
	
	public static EmailService getEmailService() {
		return instance;
	}
	
	public void addEmail(Email email) {
		if(!closed) {
			queue.addEmail(email);
		}
	}
	
	public void sendNotificationEmail() {
		if(!closed) {
			System.out.println(queue.getEmail().toString());			
		} else {
			if(!queue.isEmpty()) {
				System.out.println(queue.getEmail().toString());
			} else {
				Thread.currentThread().interrupt();
			}
		}
	}

	public void close() {
		closed = true;
	}
	
	public Queue getQueue() {
		return queue;
	}
}
